<template>
  <div class="config_container">
    <el-button size="mini" @click="handleOpen">
      <el-tooltip class="item" effect="dark" content="请选中左侧检查部门后再进行排序" placement="top-start">
        <i class="el-icon-sort">排序</i>
      </el-tooltip>
    </el-button>
    <el-dialog :visible.sync="dialogVisible" top="3%" width="31%" append-to-body :close-on-click-modal="true" :destroy-on-close="true" :before-close="handleClose" class="config_setting_dialog partSort">
      <div slot="title" class="dialog-title">
        <el-row>
          <span class="dialog-title-text">HIS申请部位排序</span>
          <span class="dialog-text">【可拖拽排序，置顶排序，输入序号排序】</span>
        </el-row>
      </div>
      <div class="sortOrders">
        <!-- <el-scrollbar style="height: 600px;" ref="scrollbar"> -->
        <el-tree
          ref="sortTree"
          node-key="id"
          style="height: 100%;"
          id="filterTree"
          class="filter-tree"
          v-loading="loading"
          :data="data"
          :props="defaultProps"
          :highlight-current="true"
          :current-node-key="currentNodeKey"
          @node-click="handleNodeClick"
          :draggable="true"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          :expand-on-click-node="false"
          @node-drag-end="handleDragEnd">
          <span ref="nodeRef" class="custom-tree-node" slot-scope="{ node, data }" @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)">
            <span>{{node.label}}</span>
            <span>
              <el-button
                style="float: right;color: #C0C4CC;"
                class="topTree"
                type="text"
                size="mini"
                v-show="data.show"
                @click="() => topData(node, data)">
                <i class="el-icon-upload2"></i>
                置顶
              </el-button>
              <el-input size="mini" style="width: 23%;float: right;height: 21px;" v-show="data.show" @focus="handleFocus" @blur="handleBlur" v-model="data.sortCode" @change="handleSort(data.sortCode, node, data)"></el-input>
            </span>
          </span>
        </el-tree>
        <!-- </el-scrollbar> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import bus from '@/api/bus.js'
// import tableStyle from '@/utils/tableStyle.js'
// import Sortable from 'sortablejs'
// import draggable from 'vuedraggable'
import {
  putSetPartOrders,
  postHisRegisterpartGetadvancepages
} from '@/api/api.js'
export default {
  props: {
    configVisible: {
      type: Boolean,
      default: false
    },
    hospitalCode: {
      type: String,
      default: ''
    },
    checkRoomValue: {
      type: String,
      default: ''
    }
  },
  // components: {
  //   draggable
  // },
  computed: {
    dialogVisible: {
      get() {
        return this.configVisible
      },
      set(val) {
        this.$emit('update:configVisible', val)
      }
    }
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          // this.getAppConfig()
        }
      },
      immediate: true
    },
    rowOrder(newOrder) {
      this.tableData = newOrder.map(index => this.tableData[index])
    }
  },
  data() {
    return {
      loading: false,
      params: {},
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentNodeKey: null,
      isDraggle: true,
      isSaveResult: true,
      scrollTimeout: null,
      savePartSort: []
    }
  },
  async created() {
    await this.$getHospitalList()
  },
  mounted() {
    bus.$on('hisIndexInfo', (data) => {
      this.params = data
      this.params.pageNumber = 1
      // console.error('hisIndexInfo=>this.params', this.params)
    })
  },
  destroyed() {
    bus.$off('hisIndexInfo')
  },
  methods: {
    // 格式化医院code
    frtHospCode(row, column, cellValue, index) {
      let name = ''
      let hospIndex = this.mx_hospitalList.findIndex(
        (item) => item.code === cellValue
      )
      if (hospIndex !== -1) {
        name = this.mx_hospitalList[hospIndex].name
      }
      return name
    },
    // 获取打开时的数据（已知数据：检查部门，检查设备）
    handleOpen() {
      if (!this.params.hospitalCode) {
        this.$message.warning('页面还未加载完毕请稍等')
        return // 结束函数的执行，不再执行后续代码
      } else if (this.params.dep == '') {
        this.$message.warning('请先点击左侧对应的检查部门')
        return // 结束函数的执行，不再执行后续代码
      } else if (this.params.modality == '') {
        this.$message.warning('请先点击左侧对应的设备类型')
        return // 结束函数的执行，不再执行后续代码
      }
      this.loading = true
      this.dialogVisible = true
      this.params.sortOrder = '2'
      // this.params.partType = 2 // 部位类型:1检查部位、2检查项目
      console.log('this.params', this.params)
      postHisRegisterpartGetadvancepages(this.params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          let test = res.content.list
          var filteredArray = []
          var smallparts = {}
          test.forEach(function (obj) {
            if (!smallparts[obj.smallpart] || smallparts[obj.smallpart].bigpart !== obj.bigpart) {
              smallparts[obj.smallpart] = obj
              filteredArray.push(obj)
            }
          })
          // 首先对 filteredArray 进行排序
          filteredArray.sort((a, b) => {
            // 按照 partSort 进行排序
            if (a.partSort !== b.partSort) {
              return a.partSort - b.partSort
            }
            // 如果 partSort 相同，则按照 sortCode 进行排序
            return a.sortCode - b.sortCode
          })
          let result = filteredArray.reduce((acc, curr, index) => {
            // 查找是否已经存在对应bigpart的对象
            let existingBigPart = acc.find(item => item.bigpart === curr.bigpart)
            if (existingBigPart) {
              // console.error('acc', acc.length, existingBigPart.children.length)
              // 如果已经存在对应bigpart的对象，则将当前的smallpart加入其children数组中
              existingBigPart.children.push({ id: curr.smallpart, label: curr.smallpart, smallpart: curr.smallpart, sortCode: existingBigPart.children.length, bigpart: curr.bigpart, show: false })
              // existingBigPart.children.sort((a, b) => a.sortOldCode - b.sortOldCode)
            } else {
              // 如果不存在对应bigpart的对象，则创建一个新的对象并加入结果数组中
              acc.push({ id: curr.bigpart, label: curr.bigpart, bigpart: curr.bigpart, sortCode: acc.length, show: false, children: [{ id: curr.smallpart, label: curr.smallpart, smallpart: curr.smallpart, sortCode: 0, bigpart: curr.bigpart, show: false }] })
            }
            return acc
          }, [])
          this.data = result
          // console.error('已经拼好的数据', this.data)let uniqueId = `level1_${curr.bigpart}_${acc.length}`;
        }
      })
    },
    // 关闭页面
    handleClose() {
      this.dialogVisible = false
    },
    // 点击节点时的触发事件
    handleNodeClick(data) {
      // const currentNode = event.target.closest('.el-tree-node__content')
      // console.error('currentNode', currentNode)
      // 滚动到当前节点的位置
      // currentNode.scrollIntoView({ behavior: 'smooth', block: 'center' })
      // const rect = currentNode.getBoundingClientRect()
    },
    handleFocus() {
      this.isDraggle = false
    },
    handleBlur() {
      this.isDraggle = true
    },
    // 判断是否允许被拖拽
    allowDrag(draggingNode) {
      return this.isDraggle
    },
    // 拖拽的时候触发的事件
    allowDrop(draggingNode, dropNode, type) {
      // console.error('树排序', draggingNode)
      // 注掉的是同级拖拽
      if (draggingNode.level === dropNode.level && draggingNode.parent === dropNode.parent) {
        this.isSaveResult = true
        return type === 'prev' || type === 'next'
      } else {
        // 不同级进行处理
        this.isSaveResult = false
        return false
      }
    },
    // 移入鼠标时显示按钮
    mouseenter(data) {
      data.show = true
    },
    // 移出鼠标时隐藏按钮
    mouseleave(data) {
      data.show = false
    },
    topData(node, data) {
      this.loading = true
      // 如果已经是第一的位置则返回：已经排序第一的不能再置顶！,排到置顶的位置需要根据他的位置进行滚轮移动
      let c = Object.assign({}, data)
      // console.error('node.parent.level', node.parent.level, node.parent.data.children[0].label, c.label)
      if (node.parent.level === 0 && this.data[0].label != c.label) {
        this.data = this.data.filter(obj => obj.label !== c.label)
        this.data.unshift(c)
        this.updateIndex(0, this.data)
      } else if (node.parent.level != 0 && node.parent.data.children[0].label != c.label) {
        node.parent.data.children = node.parent.data.children.filter(obj => obj.label !== c.label)
        node.parent.data.children.unshift(c)
        this.updateIndex(1, node.parent.data.children)
      } else {
        this.$message.warning('已经排序第一的不能再置顶！')
        // 更新 el-tree 的选中节点
      }
      this.doScroller()
    },
    // 拖拽完成的时候保存到接口中
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      // console.error('tree drag end: ', dropNode && dropNode.label, dropType, dropNode)
      // console.error('existingBigPart', dropNode.level)
      this.loading = true
      if (dropNode.level === 2) {
        const parentItem = this.data.find(item => item.bigpart === dropNode.data.bigpart)
        if (parentItem) {
          this.updateIndex(1, parentItem.children)
        }
      } else if (dropNode.level === 1) {
        this.updateIndex(0, this.data)
      }
    },
    // 保存到接口当中
    setSort(level) {
      // 置顶，输入序号，拖拽
      let roomParams = {
        hospitalCode: this.hospitalCode,
        dep: this.params.dep, // 检查部门
        modality: this.params.modality, // 检查设备 DX、CT、MR等
        list: this.savePartSort
      }
      // console.error('roomParams', roomParams)
      putSetPartOrders(roomParams).then(res => {
        this.loading = false
        // this.$emit('refresh')
        // this.dialogVisible = false
        if (res && res.code === 10000) {
          this.$message.success(res.message || '批量设置机房排序成功')
        }
        this.scrollTimeout && clearTimeout(this.scrollTimeout)
        this.isSaveResult = true
      }).catch(() => {
        this.loading = false
      })
    },
    // 输入对应位置后重置数据排序结构
    async handleSort(newVal, node, data) {
      // console.error('newVal', node.parent.level)
      this.loading = true
      let c = Object.assign({}, data)
      let selectedNodeKey = this.$refs.sortTree.getCurrentKey() // 获取当前选中节点的 key
      if (node.parent.level === 0) {
        // 第一层进行插入更改
        let parentItem = this.data
        parentItem = parentItem.filter(item => item.label != data.label)
        parentItem.splice(newVal, 0, c)
        this.updateIndex(node.parent.level, parentItem)
      } else {
        // 第二层进行插入更改
        let parentItem = this.data.find(item => item.bigpart === data.bigpart)
        parentItem.children = parentItem.children.filter(item => item.label != data.label)
        parentItem.children.splice(newVal, 0, c)
        this.updateIndex(node.parent.level, parentItem.children)
      }

      // 在重新渲染后恢复选中状态
      this.$nextTick(() => {
        this.$refs.sortTree.setCurrentKey(selectedNodeKey)
      })
      this.doScroller()
    },
    // 将数据进行重排
    updateIndex(level, data) {
      this.savePartSort = []
      let paramInput = {}
      if (level === 0) {
        data.forEach((item, index) => {
          item.sortCode = index
          item.partSort = index
          paramInput = {
            partType: 1,
            sortCode: item.sortCode,
            bigpart: item.bigpart
          }
          this.savePartSort.push(paramInput)
        })
        this.data = data
      } else {
        data.forEach((item, index) => {
          item.sortCode = index
          paramInput = {
            partType: 2,
            sortCode: item.sortCode,
            bigpart: item.bigpart,
            smallpart: item.smallpart
          }
          this.savePartSort.push(paramInput)
        })
      }
      // console.error('savePartSort', this.savePartSort)
      // console.error('this.data', this.data)
      // this.loading = false
      this.isSaveResult ? this.setSort() : this.loading = false
    },
    // 向指定节点进行滚动
    doScroller() {
      const modalElement = document.querySelector('.sortOrders .filter-tree') // 请根据实际情况获取弹窗的 DOM 元素
      this.$nextTick(() => {
        this.scrollTimeout = setTimeout(() => {
          const currentElement = modalElement.querySelector('.el-tree-node.is-current.is-focusable')
          currentElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
        }, 0)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.draggableTableBody{
  max-height: calc(100vh - 270px);
  overflow-y: auto;
}
.listBox{
  height: 52px;
  border-bottom: 1px solid #e8e8e8;
}
.listBoxItem{
  /* padding: 0px 10px; */
  flex: 1;
  cursor: pointer;
  display: flex;
  flex-direction: row;
}
.el-dialog__body{
  /* height: 500px; */
  overflow: hidden;
  overflow-y: scroll;
  overflow-x: scroll;
}
.headerBox{
  background-color: #00c0ef;
  color: #ffffff;
  padding: 0 5px;
}
.box-table td {
  padding: 10px 0px !important;
}
.dragged-row {
  background-color: #00c0ef; /* 被拖动行的背景颜色 */
  color: #ffffff;
}
/* // 拖拽 */
.dragClass {
  background-color: rgba(0, 188, 235, 0.5) !important;
  color: #0000a3 !important;
}
/* // 停靠 */
.ghostClass {
  background-color: rgba(0, 191, 243, 0.1) !important;
}
/* // 选择 */
.chosenClass:hover > td {
  background-color: rgba(0, 188, 235, 0.2) !important;
}
.partSort.config_setting_dialog{
  /deep/ .el-dialog__body{
    padding: 10px 20px;
    min-height: 230px;
    max-height: 800px;
    overflow: hidden;
    overflow-y: scroll;
    overflow-x: scroll;
  }
}
.dialog-title-text {
  font-size: 20px;
}
.dialog-text {
  color: red;
}
.partSort .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.partSort /deep/ .el-input--mini .el-input__inner {
  height: 21px;
  line-height: 21px;
  margin-top: 5px;
  margin-bottom: 2px;
}
.no-resize-input .el-input__inner {
  resize: none;
}
</style>
